package com.dal.myconsul.controller;

import cn.hutool.http.HttpRequest;
import com.dal.myconsul.domain.ServiceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
public class GatewayController {
    @Resource
    RedisTemplate redisTemplate;
    /**
     * 实现简单gateway
     * @param name
     * @param api
     */
    @RequestMapping("{name}/{api}")
    public String simpleGateway(@PathVariable("name") String name, @PathVariable("api") String api){
        // 获取redis中已注册服务
        ListOperations<String, ServiceInfo> listOps = redisTemplate.opsForList();
        var key="services_"+name;
        log.info(key);
        log.info("size {} ",listOps.size(key));
        // 根据请求的service name获取对应的服务信息
        ServiceInfo serviceInfo=listOps.index(key,-1);
        log.info("serviceInfo {} ",serviceInfo);
        if (serviceInfo !=null){
            log.info(String.valueOf(serviceInfo));
            // 拼接请求地址
            String url = "http://" + serviceInfo.getIp() + ":" + serviceInfo.getPort() + "/" + api;
            // 请求转发到该地址
            String result = HttpRequest.get(url)
                    .execute()
                    .body();
            return result;
        } else {
            // 未查到服务注册信息
            return name + " 服务尚未注册，请注册后重试";
        }
    }
}
